<template>
  <view>
    <view class="poster-modal" v-if="visible" @click="onClose">
      <view class="poster-container" @click.stop>
        <view class="poster-header">
          <text class="poster-title">{{ posterTitle }}</text>
          <view class="close-btn" @click="onClose">
            <text class="close-icon">×</text>
          </view>
        </view>

        <view class="poster-content">
          <view class="poster-main">
            <view class="poster-image-section">
              <image :src="cover || '/static/image/logo.png'" class="poster-image" mode="aspectFit"></image>
            </view>

            <view class="poster-info-section">
              <view class="poster-details">
                <text class="poster-travel-name">{{ title }}</text>
                <text class="poster-sku-name">{{ skuName }}</text>
                <text class="poster-date">{{ dateText }}</text>
              </view>

              <view class="poster-qrcode">
                <image :src="qrcode || '/static/image/logo.png'" class="qrcode-image" mode="aspectFit"></image>
                <text class="qrcode-tip">{{ distributorName }}</text>
              </view>
            </view>
          </view>

          <view class="poster-actions">
            <button class="save-poster-btn" @click="savePoster">保存海报</button>
            <button class="share-btn" open-type="share">分享给好友</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 隐藏的canvas用于绘制海报 -->
    <canvas id="share-poster-canvas" type="2d"
      style="position: fixed; top: -9999px; left: -9999px; width: 640rpx; height: 1000rpx;"></canvas>
  </view>
</template>

<script>
export default {
  name: 'SharePoster',
  props: {
    visible: { type: Boolean, default: false },
    posterTitle: { type: String, default: '分享海报' },
    cover: { type: String, default: '' },
    title: { type: String, default: '' },
    skuName: { type: String, default: '' },
    dateText: { type: String, default: '' },
    qrcode: { type: String, default: '' },
    distributorName: { type: String, default: '' },
    shareUrl: { type: String, default: '' }
  },
  emits: ['close', 'uploaded'],
  methods: {
    onClose() {
      this.$emit('close');
    },
    // 外部可调用：生成海报。isSave=false 仅生成并上传，不保存到相册
    generatePoster(isSave = true) {
      const query = uni.createSelectorQuery().in(this);
      query.select('#share-poster-canvas').fields({ node: true, size: true }).exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');

        const canvasWidth = 640;
        const canvasHeight = 1000;
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;

        ctx.fillStyle = '#FFFFFF';
        ctx.fillRect(0, 0, canvasWidth, canvasHeight);

        const coverImg = canvas.createImage();
        coverImg.onload = () => {
          // 计算图片绘制尺寸（aspectFit效果）
          const imageWidth = coverImg.width;
          const imageHeight = coverImg.height;
          const imageRatio = imageWidth / imageHeight;
          const canvasImageHeight = 640;
          const canvasImageWidth = canvasWidth;
          const canvasImageRatio = canvasImageWidth / canvasImageHeight;
          
          let drawWidth, drawHeight, drawX, drawY;
          
          if (imageRatio > canvasImageRatio) {
            // 图片更宽，以宽度为准
            drawWidth = canvasImageWidth;
            drawHeight = canvasImageWidth / imageRatio;
            drawX = 0;
            drawY = (canvasImageHeight - drawHeight) / 2;
          } else {
            // 图片更高，以高度为准
            drawHeight = canvasImageHeight;
            drawWidth = canvasImageHeight * imageRatio;
            drawX = (canvasImageWidth - drawWidth) / 2;
            drawY = 0;
          }
          
          // 绘制白色背景
          ctx.fillStyle = '#FFFFFF';
          ctx.fillRect(0, 0, canvasWidth, canvasHeight);
          
          // 绘制图片（保持比例）
          ctx.drawImage(coverImg, drawX, drawY, drawWidth, drawHeight);

          // 计算文案区域起始位置
          const textStartY = canvasImageHeight + 32;
          const textMaxWidth = canvasWidth - 64;
          const textMaxHeight = canvasHeight - textStartY - 200; // 预留二维码区域

          // 标题
          ctx.fillStyle = '#333333';
          ctx.font = 'bold 28px sans-serif';
          ctx.textBaseline = 'top';
          ctx.textAlign = 'left';
          const titleLines = this.getTextLines(ctx, this.title || '', textMaxWidth, 2);
          titleLines.forEach((line, index) => {
            const y = textStartY + index * 40;
            if (y + 40 <= canvasHeight - 200) { // 确保不超出画布
              ctx.fillText(line, 32, y);
            }
          });

          // SKU
          ctx.fillStyle = '#666666';
          ctx.font = '18px sans-serif';
          const skuY = textStartY + titleLines.length * 40 + 16;
          if (skuY + 24 <= canvasHeight - 200) {
            ctx.fillText(this.skuName || '', 32, skuY);
          }

          // 日期
          ctx.fillStyle = '#999999';
          ctx.font = '16px sans-serif';
          const dateY = skuY + 24 + 8;
          if (dateY + 20 <= canvasHeight - 200) {
            ctx.fillText(this.dateText || '', 32, dateY);
          }

          // 二维码
          const qrcodeImg = canvas.createImage();
          qrcodeImg.onload = () => {
            const qrcodeSize = 120;
            const qrcodeX = (canvasWidth - qrcodeSize) / 2;
            const qrcodeY = canvasHeight - 32 - qrcodeSize - 32;
            ctx.drawImage(qrcodeImg, qrcodeX, qrcodeY, qrcodeSize, qrcodeSize);

            // 分享人
            ctx.fillStyle = '#999999';
            ctx.font = '24px sans-serif';
            ctx.textAlign = 'center';
            ctx.fillText(this.distributorName || '', qrcodeX + qrcodeSize / 2, qrcodeY + qrcodeSize + 16);

            this.exportAndUpload(canvas, isSave);
          };
          qrcodeImg.onerror = () => {
            // 二维码失败也继续导出
            this.exportAndUpload(canvas, isSave);
          };
          qrcodeImg.src = this.qrcode || '/static/image/logo.png';
        };
        coverImg.onerror = () => {
          // 无封面时采用纯色背景并写字
          this.drawPosterWithoutCover(ctx, canvas, canvasWidth, canvasHeight, isSave);
        };
        coverImg.src = this.cover || '/static/image/logo.png';
      });
    },
    savePoster() {
      uni.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            uni.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                this.generatePoster(true);

              },
              fail: () => {
                uni.showModal({
                  title: '提示',
                  content: '需要相册权限才能保存海报，请在设置中开启',
                  confirmText: '去设置',
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      uni.openSetting();
                    }
                  }
                });
              }
            });
          } else {
            this.generatePoster(true);
          }
        },
        fail: () => {
          this.generatePoster(true);
        }
      });
    },
    exportAndUpload(canvas, isSave) {
      uni.canvasToTempFilePath({
        canvas: canvas,
        success: (res) => {
          const tempPath = res.tempFilePath;
          uni.showLoading({
            title: '保存中',
            mask: true,
          });
          // 上传到服务器后把 URL 回传给父组件
          this.uploadPosterImage(tempPath).then((url) => {
            this.$emit('uploaded', url);
          }).catch(() => {
            // 忽略上传失败，仍可保存
          }).finally(() => {
            uni.hideLoading();
            if (!isSave) return;
            uni.saveImageToPhotosAlbum({
              filePath: tempPath,
              success: () => {
                uni.showToast({ title: '海报已保存到相册', icon: 'success' });
              },
              fail: () => {
                uni.showToast({ title: '保存失败，请检查相册权限', icon: 'none' });
              }
            });
          });
        },
        fail: () => {
          uni.showToast({ title: '生成海报失败', icon: 'none' });
        }
      });
    },
    uploadPosterImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: this.$api.uploadImage,
          filePath: filePath,
          name: 'file',
          success: (uploadFileRes) => {
            try {
              const data = JSON.parse(uploadFileRes.data);
              const url = data.data && data.data.url ? data.data.url : '';
              if (url) {
                resolve(url);
              } else {
                reject(new Error('empty url'));
              }
            } catch (e) {
              reject(e);
            }
          },
          fail: (err) => reject(err)
        });
      });
    },
    getTextLines(ctx, text, maxWidth, maxLines) {
      const words = (text || '').split('');
      const lines = [];
      let currentLine = '';
      for (let i = 0; i < words.length; i++) {
        const testLine = currentLine + words[i];
        const metrics = ctx.measureText(testLine);
        if (metrics.width > maxWidth && currentLine !== '') {
          lines.push(currentLine);
          currentLine = words[i];
          if (lines.length >= maxLines) break;
        } else {
          currentLine = testLine;
        }
      }
      if (currentLine !== '' && lines.length < maxLines) lines.push(currentLine);
      return lines;
    },
    drawPosterWithoutCover(ctx, canvas, canvasWidth, canvasHeight, isSave) {
      // 绘制渐变背景
      const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight);
      gradient.addColorStop(0, '#ff6b35');
      gradient.addColorStop(1, '#ff8c42');
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);

      // 计算文案区域
      const textStartY = 32;
      const textMaxWidth = canvasWidth - 64;
      const textMaxHeight = canvasHeight - textStartY - 200; // 预留二维码区域

      // 标题
      ctx.fillStyle = '#FFFFFF';
      ctx.font = 'bold 28px sans-serif';
      ctx.textBaseline = 'top';
      ctx.textAlign = 'left';
      const titleLines = this.getTextLines(ctx, this.title || '', textMaxWidth, 2);
      titleLines.forEach((line, index) => {
        const y = textStartY + index * 40;
        if (y + 40 <= canvasHeight - 200) { // 确保不超出画布
          ctx.fillText(line, 32, y);
        }
      });

      // SKU
      ctx.font = '18px sans-serif';
      const skuY = textStartY + titleLines.length * 40 + 16;
      if (skuY + 24 <= canvasHeight - 200) {
        ctx.fillText(this.skuName || '', 32, skuY);
      }

      // 日期
      ctx.font = '16px sans-serif';
      const dateY = skuY + 24 + 8;
      if (dateY + 20 <= canvasHeight - 200) {
        ctx.fillText(this.dateText || '', 32, dateY);
      }

      // 二维码
      const qrcodeImg = canvas.createImage();
      qrcodeImg.onload = () => {
        const qrcodeSize = 120;
        const qrcodeX = (canvasWidth - qrcodeSize) / 2;
        const qrcodeY = canvasHeight - 32 - qrcodeSize - 32;
        ctx.drawImage(qrcodeImg, qrcodeX, qrcodeY, qrcodeSize, qrcodeSize);

        // 分享人
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '24px sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText(this.distributorName || '', qrcodeX + qrcodeSize / 2, qrcodeY + qrcodeSize + 16);

        this.exportAndUpload(canvas, isSave);
      };
      qrcodeImg.onerror = () => {
        // 二维码失败也继续导出
        this.exportAndUpload(canvas, isSave);
      };
      qrcodeImg.src = this.qrcode || '/static/image/logo.png';
    }
  }
}
</script>

<style lang="scss" scoped>
.poster-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .poster-container {
    width: 640rpx;
    height: 1000rpx;
    background: #FFFFFF;
    border-radius: 24rpx;
    overflow: hidden;
    position: relative;

    .poster-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      border-bottom: 1rpx solid #f0f0f0;

      .poster-title {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }

      .close-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: #f5f5f5;

        .close-icon {
          font-size: 40rpx;
          color: #666666;
          line-height: 1;
        }
      }
    }

    .poster-content {
      height: calc(100% - 124rpx);
      display: flex;
      flex-direction: column;

      .poster-main {
        flex: 1;
        display: flex;
        flex-direction: column;

        .poster-image-section {
          width: 100%;
          height: 480rpx;

          .poster-image {
            width: 100%;
            height: 100%;
          }
        }

        .poster-info-section {
          flex: 1;
          padding: 32rpx;
          display: flex;
          align-items: center;
          gap: 32rpx;

          .poster-details {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 16rpx;

            .poster-travel-name {
              font-size: 28rpx;
              color: #333333;
              font-weight: bold;
              line-height: 1.4;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              overflow: hidden;
            }

            .poster-sku-name {
              font-size: 18rpx;
              color: #666666;
              line-height: 1.4;
            }

            .poster-date {
              font-size: 16rpx;
              color: #999999;
            }
          }

          .poster-qrcode {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 16rpx;

            .qrcode-image {
              width: 120rpx;
              height: 120rpx;
              border-radius: 12rpx;
              border: 2rpx solid #f0f0f0;
            }

            .qrcode-tip {
              font-size: 24rpx;
              color: #999999;
              text-align: center;
            }
          }
        }
      }

      .poster-actions {
        padding: 32rpx;
        display: flex;
        gap: 24rpx;
        border-top: 1rpx solid #f0f0f0;

        .save-poster-btn,
        .share-btn {
          flex: 1;
          height: 64rpx;
          border-radius: 32rpx;
          font-size: 24rpx;
          font-weight: bold;
          border: none;
          display: flex;
          align-items: center;
          justify-content: center;
          &::after {
            border: none !important;
          }
        }

        .save-poster-btn {
          background: #f5f5f5;
          color: #666666;

          &:active {
            background: #e0e0e0;
          }
        }

        .share-btn {
          background: #ff6b35;
          color: #FFFFFF;

          &:active {
            background: #e55a2b;
          }
        }
      }
    }
  }
}
</style> 